<?php
/**
 * @author Dave Newsom
 * @name MySQLAdapter
 * @version 3.0
 * @copyright Copyright (c) 2010
 */

require_once('libraries/database/DBManager.php');
class MySQLAdater implements DBManager {
	private $_connection;
	private $result;
    private $rows;
    private $data;
    private $affectedRows;
	private $user;
    private $pass;
    private $host;
    private $db;
    private $errors = array();

	public function __construct($user, $pass, $host, $db) {
		$this->user = $user;
		$this->pass = $pass;
		$this->host = $host;
		$this->db = $db;

		$this->connect();
	}

    public function getData() {
        return $this->data;
    }

    public function getRows() {
        return $this->rows;
    }

    public function getAffectedRows() {
        return $this->affectedRows;
    }

    public function getResult() {
        return $this->result;
    }

	/**
	 * Connect to the database
	 */
	public function connect() {
		$this->_connection = @mysql_connect($this->host, $this->user, $this->pass) or $this->errorHandler("Unable to connect to MySQL server: {$this->host}.", "");
		$this->selectDB($this->db);
	}
	
	/**
	 * Disconnect from the database
	 */
	public function disconnect() {
		@mysql_close($this->_connection()) or $this->errorHandler("Unable to disconnect from MySQL server: {$this->host}.", "");
	}

	/**
	 * Select a database
	 *
	 * @param string $db
	 */
	protected function selectDB($db) {
		@mysql_select_db($db, $this->_connection) or $this->errorHandler("Unable to select database: {$db}.", "");
	}

	/**
	 * Execute query and return results
	 *
	 * @param string $query
	 */
	private function execute($query) {
		$this->result = @mysql_query($query, $this->_connection) or $this->errorHandler("Unable to perform update.", $query);
		$this->rows = @mysql_num_rows($this->result);
		$this->affectedRows = @mysql_affected_rows($this->_connection);
	}

	/**
	 * This function is for the optimazation of tables.
	 *
	 * @param string $table
	 */
	public function optimize($table) {
		$query = "OPTIMIZE TABLE " . $table;
		$this->result = $this->execute($query);
	}

	/**
	 * This function is the query will return multiple rows.
	 * Use the Fetch routine to loop through those rows.
	 *
	 * @param string $query
	 */
	public function query($query) {
		$this->execute($query);
	}

	/**
	 * This function if the query will only return a single data element.
	 *
	 * @param string $query
	 * @return unknown
	 */
	public function queryItem($query) {
		$this->execute($query);
		$this->data = @mysql_fetch_array($this->result) or $this->errorHandler("Unable to fetch data from QueryItem.", $query);
		return ($this->data[0]);
	}

	/**
	 * This function is useful if the query will only return a single row.
	 *
	 * @param string $query
	 * @return array
	 */
	public function queryRow($query) {
		$this->execute($query);
		$this->data = @mysql_fetch_array($this->result) or $this->errorHandler("Unable to fetch data from QueryRow.", $query);
		return ($this->data);
	}

	/**
	 * This function is used to select a row from a result set.
	 *
	 * @param int $row
	 */
	public function fetch($row) {
		@mysql_data_seek($this->result, $row) or $this->errorHandler("Unable to seek data row: {$row}", "");
		$this->data = @mysql_fetch_array($this->result) or $this->errorHandler("Unable to fetch row: {$row}", "");
	}

	/**
	 * Insert value into table
	 *
	 * @param string $table
	 * @param array $values ($column => $value)
	 */
	public function insert($table, array $values) {
		try {
			$query = "INSERT INTO {$table} SET";
			foreach ($values as $column => $value) {
				$query .= " {$column}='{$value}',";
			}
			$this->execute(substr($query, 0, -1));
		} catch (Exception $e) {
			$this->errorHandler($e->getMessage(), $query);
		}
	}

	public function insertID() {
		return mysql_insert_id();
	}

	/**
	 * Update value on table
	 *
	 * @param string $table
	 * @param array $values ($column => $value)
	 * @param array $search ($column => $value)
	 */
	public function update($table, array $values, array $search) {
		try {
			$query = "UPDATE {$table} SET";
			foreach ($values as $column => $value) {
				if ($value == 'NOW()') {
					$query .= " {$column}={$value},";
				} else {
				    $query .= " {$column}='{$value}',";
				}
			}
			$query = substr($query, 0, -1) . " WHERE";
			foreach ($search as $column => $value) {
				$query .= " {$column} LIKE '{$value}' AND";
			}
			$this->execute(substr($query, 0, -4));
		} catch (Exception $e) {
			$this->errorHandler($e->getMessage(), $query);
		}
	}

	/**
	 * Delete value from table
	 *
	 * @param string $table
	 * @param array $search ($column => $value)
	 */
	public function delete($table, array $search) {
		try {
			$query = "DELETE FROM {$table} WHERE";
			foreach ($search as $column => $value) {
				$query .= " {$column} LIKE '{$value}' AND";
			}
			$this->execute(substr($query, 0, -4));
		} catch (Exception $e) {
			$this->errorHandler($e->getMessage(), $query);
		}
	}

	/**
	 * Check if values exist
	 *
	 * @param array $table
	 * @param array $search
	 * @return boolean
	 */
	public function checkExists(array $tables, array $search) {
		try {
			$query = "SELECT";
			foreach ($search as $column => $value) {
				$query .= " {$column},";
			}
			$query = substr($query, 0, -1) . " FROM";
			foreach ($tables as $key => $table) {
				$query .= " {$table},";
			}
			$query = substr($query, 0, -1) . " WHERE";
			foreach ($search as $column => $value) {
				$query .= " {$column} LIKE '{$value}' AND";
			}
			$this->execute(substr($query, 0, -4));

			if ($this->affectedRows > 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception $e) {
			$this->errorHandler($e->getMessage(), $query);
		}
	}

	/**
	 * Clean string for sql injection
	 *
	 * @param string $text
	 * @return string
	 */
	public function sterilize($text) {
		$cleanText = mysql_real_escape_string($text);
		return $cleanText;
	}

	/**
	 * Format sql errors and display
	 *
	 * @param string $msg
     * @param string $sql
	 */
	private function errorHandler($msg, $sql) {
		$this->errors[] = array('message' => $msg, 'sql' => $sql, 'errors' => mysql_error());
	}

}
?>
